package data

import (
	"fmt"
	"regexp"
	"strconv"
	"strings"
)

//将{{.AppName}}-{{.Method}}解析为[AppName,Method]的数组
func FormatLegend(legend string) []string {
	if len(legend) == 0 {
		return []string{"__name__"}
	}
	reg := regexp.MustCompile("\\{{2}\\.{1}[^}]*\\}{2}")
	mat := reg.FindAllString(legend, -1)
	if len(mat) == 0 {
		return []string{"__name__"}
	}
	result := make([]string, 0)
	for _, s := range mat {
		result = append(result, s[3:len(s)-2])
	}
	return result
}

// 匹配api 类似app ="{{.AppName}}", method="{{.Method}}", uri="{{.Uri}}"
func MatchApi(s string) []string {
	reg := regexp.MustCompile("[^{,=]*=\\s*\"\\{{2}\\.{1}[^}]*\\}{2}\"\\s*,?")
	mat := reg.FindAllString(s, -1)
	return mat
}

func UnFormatLegend(legend string) string {
	if !strings.Contains(legend, "{{") {
		return legend
	}
	return legend[3:strings.Index(legend, "}")]
}

func ToString(bs []uint8) string {
	var bytes []byte
	for _, b := range bs {
		bytes = append(bytes, b)
	}
	return string(bytes)
}

func Compute(str string) float64 {
	if !strings.Contains(str, "*") {
		result, _ := strconv.ParseFloat(str, 10)
		return result
	} else {
		split := strings.Split(str, "*")
		var result float64 = 1
		for _, s := range split {
			i, _ := strconv.ParseFloat(strings.TrimSpace(s), 10)
			result *= i
		}
		return result
	}
}

func FormatValue(value interface{}) string {
	var temp = ""
	if i, ok := value.(float64); ok {
		temp = fmt.Sprintf("%.3f", i)
	} else {
		temp = value.(string)
	}
	return temp
}
